package com.dpiinc.TechPage.viewmodel

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import com.dpiinc.TechPage.OfflineDataMergeHelper
import com.dpiinc.TechPage.api.EditNoteApi
import com.dpiinc.TechPage.constants.FileType
import com.dpiinc.TechPage.oss.UploadTask
import com.dpiinc.TechPage.repository.EditNoteRepository
import com.dpiinc.TechPage.repository.NetworkState
import com.dpiinc.TechPage.room.RoomAiWriterDatabase
import com.dpiinc.TechPage.room.bean.NoteEntity
import com.dpiinc.TechPage.utils.DateUtils
import com.beiji.lib.pen.cache.PenCacheManager

/**
 * 离线笔迹 ViewModel
 * Created by X on 2018/7/21.
 */
class OfflineDataViewModel(application: Application) : AndroidViewModel(application) {
    val note: NoteEntity = NoteEntity(EditNoteViewModel.generateNoteId())
    var isSaveAsNewNote: Boolean = true
    var lastNote: NoteEntity? = null
    private val repository = EditNoteRepository(RoomAiWriterDatabase.getInstance(application), EditNoteApi.create())

    init {
        note.createTime = DateUtils.getCurrentTimeMillis()
        note.modifyTime = DateUtils.getCurrentTimeMillis()
        lastNote = repository.getLastNote()
    }

    private val saveTrigger = MutableLiveData<NoteEntity>()
    private val apiResult = Transformations.map(saveTrigger) {
        repository.save(it)
    }

    val networkState: LiveData<NetworkState> = Transformations.switchMap(apiResult) { it }

    fun save() {
        if (isSaveAsNewNote) {
            saveAsNewNote()
        } else {
            saveToLastNote()
        }
    }

    private fun saveAsNewNote() {
        if (note.noteName.isNullOrEmpty()) {
            note.noteName = EditNoteViewModel.generateNoteName()
        }
        val createTime = DateUtils.getCurrentTimeMillis()
        note.createTime = createTime
        note.modifyTime = createTime

        addCacheToUpdateTask(note.noteId)
        saveTrigger.value = note
    }

    private fun saveToLastNote() {
        if (lastNote == null) {
            saveAsNewNote()
            return
        }
        lastNote?.let {
            OfflineDataMergeHelper.merge(it.noteId, note.noteId) {
                addCacheToUpdateTask(it.noteId)
                it.modifyTime = DateUtils.getCurrentTimeMillis()
                saveTrigger.value = it
            }
        }
    }

    private fun addCacheToUpdateTask(noteId: String) {
        val createTime = DateUtils.getCurrentTimeMillis()
        PenCacheManager.instance.loadCache(noteId) { noteCacheModel ->
            val dotFile = noteCacheModel.getCacheFile()
            val dotUploadTask = UploadTask(noteId, FileType.DOT_FILE).apply {
                fileName = dotFile.name
                filePath = dotFile.path
                time = createTime
            }
            repository.insertUploadTask(dotUploadTask)
            val previewFile = noteCacheModel.getPreviewFile()
            val previewUploadTask = UploadTask(noteId, FileType.IMG_FILE).apply {
                fileName = previewFile.name
                filePath = previewFile.path
                time = createTime
            }
            repository.insertUploadTask(previewUploadTask)
        }
    }

    fun delete() {
        repository.delete(note)
    }

}